<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NSelect,
  NPagination,
  useDialog,
  type TreeSelectOption,
  NModal,
  NForm,
  NFormItem,
  type FormInst
} from 'naive-ui'
import { h, onMounted, reactive, ref, onBeforeUnmount, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import type { UserTableRowModel } from '@/api/user'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
// import type { InstitutionTreeModel } from '@/api/sysInstitution'
import ModalCard from '@/components/ModalCard.vue'
import { useRouter } from 'vue-router'
import useFlush from '@/hooks/useFlush'

useFlush('flushUser', () => queryTableData(false))

const passwordValidator = (_: any, value: string) => {
  if (!value) return new Error('密码为必填项，请输入密码')
  if (!/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).+$/.test(value)) {
    return new Error('密码必须包含大小写字母和数字')
  }
  if (value.length < 8) return new Error('密码长度不能小于8位')
  return true
}

const message = useMessage()
const dialog = useDialog()
const router = useRouter()

const bbgDeptList: any = ref([])
const getBbgDeptList = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'overTime',
    api: 'BbgDeptList'
  })
  if (error) return message.error(error.message)
  bbgDeptList.value = res.data
}

// const treeOptions = shallowRef<InstitutionTreeModel[]>([])
// const treeLoading = ref(false)
// const queryTreeOptions = async () => {
//   try {
//     treeLoading.value = true
//     const [error, res] = await sendRequest<HttpResponse<InstitutionTreeModel[]>>({
//       module: 'sysInstitution',
//       api: 'getTree'
//     })

//     if (error) return message.error(error.message)
//     if (res.code !== 0) return message.error(res.msg)
//     treeOptions.value = res.data
//   } catch (error) {
//     console.log(error)
//   } finally {
//     treeLoading.value = false
//   }
// }

const form = reactive({
  name: null,
  deptId: null
})

const modalVisible = ref(false)
const passwordForm = reactive({
  password: null,
  confirmPassword: null
})
const formInst = ref<FormInst | null>(null)
const checkedIds = ref<number[]>([])
const submitLoading = ref(false)
const handleSubmit = () => {
  if (!checkedIds.value.length) return message.error('请先勾选用户')

  formInst.value?.validate(async (error) => {
    if (error) return

    try {
      submitLoading.value = true
      const [err, res] = await sendRequest({
        module: 'user',
        api: 'setPassword',
        override: {
          data: {
            password: passwordForm.password,
            newPassword: passwordForm.confirmPassword,
            userIds: checkedIds.value
          }
        }
      })
      if (err) throw err
      if (res.code !== 0) throw new Error(res.msg)
      message.success(res.msg)
      modalVisible.value = false
    } catch (error: any) {
      message.error(error.message)
    } finally {
      submitLoading.value = false
    }
  })
}

const tableData = ref<UserTableRowModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
const columns: DataTableColumns<UserTableRowModel> = [
  {
    type: 'selection'
  },
  {
    title: '员工编号',
    key: 'userNumber',
    width: 100,
    align: 'center'
  },
  {
    title: '姓名',
    key: 'userName',
    minWidth: 100,
    align: 'center'
  },
  {
    title: '部门',
    key: 'deptName',
    align: 'center'
  },
  {
    title: '手机号',
    key: 'phone',
    minWidth: 100,
    align: 'center'
  },
  {
    title: '身份证号',
    key: 'idNumber',
    width: 200,
    align: 'center'
  },
  {
    title: '性别',
    key: 'sex',
    width: 80,
    align: 'center',
    render: ({ sex }) => (sex === 1 ? '男' : sex === 2 ? '女' : '')
  },
  {
    title: '职位',
    key: 'position',
    align: 'center'
  },
  {
    title: '操作',
    key: 'cz',
    align: 'center',
    width: 250,
    fixed: 'right',
    render(e) {
      console.log(e)

      return h('div', null, [
        h(
          NButton,
          {
            style: 'margin-right: 6px',
            quaternary: true,
            color: '#6CB187',
            onClick: () => {
              router.push({
                name: 'editUser',
                params: {
                  id: e.id
                },
                query: {
                  redirect: router.currentRoute.value.fullPath
                }
              })
            }
          },
          {
            default: () => '编辑'
          }
        ),
        h(
          NButton,
          {
            quaternary: true,
            color: '#FD4A29',
            onClick: () => {
              dialog.warning({
                title: '警告',
                content: '删除用户后，将不能登录，是否确定删除?',
                positiveText: '确定',
                negativeText: '取消',
                onPositiveClick: () => {
                  sendRequest({
                    module: 'user',
                    api: 'delete',
                    override: {
                      data: [e.id]
                    }
                  })
                    .then(() => {
                      queryTableData()
                    })
                    .catch(() => {
                      message.error('删除失败!')
                    })
                }
              })
            }
          },
          {
            default: () => '删除'
          }
        )
      ])
    }
  }
]

// 获取数据列表
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<UserTableRowModel>>({
    module: 'user',
    api: 'list',
    override: {
      params: {
        ...form,
        // institutionIdListStr: deptIds?.join(','),
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false

  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}


onMounted(() => {
  window.addEventListener('keyup', keyUpDown, false)
  getBbgDeptList()
  queryTableData()
})
onBeforeUnmount(() => {
  dialog.destroyAll()
})

const keyUpDown = (e: any) => e.key == 'Enter' && queryTableData(true)
onDeactivated(() => {
  window.removeEventListener('keyup', keyUpDown, false)
  dialog.destroyAll()
})
</script>

<template>
  <TableView class="userm">
    <template #form>
      <NSpace align="center" class="userm-search">
        <NInput v-model:value="form.name" clearable placeholder="姓名或手机号" style="--n-height: 44rem" />
        <NSelect v-model:value="form.deptId" clearable filterable placeholder="部门"
          :options="(bbgDeptList as unknown as TreeSelectOption[])" key-field="value" label-field="name" />
        <NButton @click="queryTableData(true)" :disabled="tableLoading" :loading="tableLoading" color="#6CB187" ghost
          style="height: 44rem; width: 78rem">
          查询
        </NButton>
        <NButton color="#5FB17F" style="height: 44rem; width: 78rem" @click="
          $router.push({
            name: 'addUser',
            query: {
              redirect: $route.fullPath
            }
          })
          ">
          新增
        </NButton>
        <NButton color="#5FB17F" style="height: 44rem" :disabled="!checkedIds.length" @click="modalVisible = true">
          设置密码
        </NButton>
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table v-bind="props" :data="tableData" :columns="columns" :row-key="(row) => row.id"
        :checked-row-keys="checkedIds" @update:checked-row-keys="checkedIds = $event as number[]" :loading="tableLoading"
        bordered />
    </template>
    <template #pagination>
      <NPagination show-size-picker show-quick-jumper :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount" :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize" @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize">
        <template #prefix>共{{ paginationReactive.itemCount }}条</template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <ModalCard title="设置密码" action @submit="handleSubmit" @close="
                            ; (modalVisible = false), (passwordForm.password = passwordForm.confirmPassword = null)
      ">
      <div class="password">
        <NForm :model="passwordForm" label-width="90rem" ref="formInst" class="password-form" label-placement="left">
          <NFormItem label="新密码" path="password" :rule="{
            required: true,
            validator: passwordValidator,
            trigger: ['input', 'blur']
          }">
            <NInput type="password" v-model:value="passwordForm.password" show-password-on="click" />
          </NFormItem>
          <NFormItem label="确认密码" path="confirmPassword" :rule="[
            {
              required: true,
              validator: (_, value) => value === passwordForm.password,
              message: '两次输入的密码不一致',
              trigger: ['input', 'blur']
            },
            {
              required: true,
              validator: passwordValidator,
              trigger: ['input', 'blur']
            }
          ]">
            <NInput type="password" show-password-on="click" v-model:value="passwordForm.confirmPassword" />
          </NFormItem>
        </NForm>
      </div>
    </ModalCard>
  </NModal>
</template>

<style scoped lang="scss">
.userm {
  padding: 29rem 20rem 42rem 30rem;
  gap: 24rem 0;
  color: rgba(0, 0, 0, 0.85);

  .userm-search {

    :deep(.n-tree-select .n-base-selection),
    :deep(.n-select .n-base-selection) {
      --n-height: 44rem !important;
    }
  }
}

.password {
  padding: 25rem 56rem 0 36rem;

  &-form {
    padding: 25rem 33rem 10rem 20rem;

    .n-input {
      width: 200rem;
    }
  }
}
</style>
